#!/usr/bin/env python2

import sys
import os
import argparse

from Ump.common import remote 
from Ump import utils
from Ump import defs
from Ump.scripts.initdb import InitDbShell
from Ump.scripts.upgradedb import UpgradeDbShell
from Ump.controller_server import ControllerDaemon
from Umpweb.web_server import WebServerDaemon
from Ump.ctrl.ha import DeployHA


class CtrlManage(object):
    
    def sshkey(self, args):
        return remote.ssh_key(args.host, args.password)

    def upgradedb(self, args):
        UpgradeDbShell().main()

    def initdb(self, args):
        InitDbShell().main(args=args)

    def start_controller(self, args):
        controller_daemon = ControllerDaemon()
        controller_daemon.start()

    def stop_controller(self, args):
        controller_daemon = ControllerDaemon()
        controller_daemon.stop()

    def test_controller(self, args):
        controller_daemon = ControllerDaemon()
        controller_daemon.test()

    def start_ui(self, args):
        ui_daemon = WebServerDaemon()
        ui_daemon.start()

    def stop_ui(self, args):
        ui_daemon = WebServerDaemon()
        ui_daemon.stop()

    def test_ui(self, args):
        ui_daemon = WebServerDaemon()
        ui_daemon.test()

    def deploy_ha(self, args):

        deploy_ha = DeployHA()
        deploy_ha.run(args)

    def recover_ha(self, args):
        deploy_ha = DeployHA()
        deploy_ha.recover_ha(args)

    def set_sso(self, args):
        ui_config = "%s/ui.conf" % (defs.ETC_DIR_PATH)
        set_sso_cmd="""
        #!/bin/bash 
        
        CONFIGFILE=%s
        CONFIG=$(cat $CONFIGFILE)
        
        if [[ $CONFIG =~ "is_fusionstack_sso" ]];
        then
            # sed -i
            echo 'mingpeng'
            sed -i '/is_fusionstack_sso/s/.*/is_fusionstack_sso=%s/' $CONFIGFILE
        else 
            # sed -i '$a'
            sed -i '$a is_fusionstack_sso=%s' $CONFIGFILE
        fi
        """ % (ui_config, args.stat, args.stat)

        if args.stat not in ['on', 'off']:
            raise Exception("sso stat must be on or off")
        utils._exec_pipe(set_sso_cmd, is_raise=True)



def main():
    parser = argparse.ArgumentParser(
        prog ='ump-ctrl',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        add_help=False,
    )

    subparsers = parser.add_subparsers(dest='subcommand',metavar='<subcommand>')

    mysql_parser = subparsers.add_parser('initdb', help='init database')
    mysql_parser.add_argument('-s', '--server', metavar='<user>', default='mysql', help='sql server name')
    mysql_parser.add_argument('-f', '--force',  action='store_true', default=False, help='developer method')
    mysql_parser.add_argument('-u', '--user', metavar='<user>', required=True, help='mysql user name')
    mysql_parser.add_argument('-p', '--password', nargs="?", metavar='<password>', help='mysql password')
    mysql_parser.add_argument('-d', '--database', metavar='<database>', required=True, help='mysql database')
    mysql_parser.add_argument('--host', metavar='<host>', default='127.0.0.1', help='mysql host')
    mysql_parser.add_argument('--port', type=int, metavar='<port>', default=3306, help='mysql port')

    mysql_parser = subparsers.add_parser('upgradedb', help='upgrade database')

    controller_parser = subparsers.add_parser('start_controller', help='start controller')
    controller_parser = subparsers.add_parser('stop_controller', help='stop controller')
    controller_parser = subparsers.add_parser('test_controller', help='test controller')

    ui_parser = subparsers.add_parser('start_ui', help='start ui')
    ui_parser = subparsers.add_parser('stop_ui', help='stop ui')
    ui_parser = subparsers.add_parser('test_ui', help='test ui')


    mysql_parser = subparsers.add_parser('sshkey', help='ssh authentication key')
    mysql_parser.add_argument('-H', '--host', metavar='<host>', required=True, help='host address')
    mysql_parser.add_argument('-p', '--password', nargs="?", metavar='<password>', help='host password')

    mysql_parser = subparsers.add_parser('deploy_ha', help='deploy ha')
    mysql_parser.add_argument('--host1-info', metavar='<host1-info>', required=True, help="format: 'root:password@ip_address'")
    mysql_parser.add_argument('--host2-info', nargs="?", metavar='<host2-info>', help="format: 'root:password@ip_address'")
    mysql_parser.add_argument('--vip', nargs="?", metavar='<virtual_ip_address>', required=True, help="IP Address")
    mysql_parser.add_argument('--ethdev', nargs="?", metavar='<ethdev>', default='ens33', help="eth device name")
    mysql_parser.add_argument('--vip_aliasing', nargs="?", metavar='<vip_aliasing>', default='2', help="Aliasing for vip, e.g.:eth0:2, 2 is the aliasing name")
    mysql_parser.add_argument('--debug',  action='store_true', default=False, help='whether open debug mode')
    mysql_parser.add_argument('--vrid', nargs="?", metavar='<virtual_router_id>', default=None, help="keepalived virtual_router_id")
    mysql_parser.add_argument('--gateway', nargs="?", metavar='<gateway_ip>', default=None, help="The Gateway IP Address used for mariadb-galera vote primary node")
    mysql_parser.add_argument('--mysql_root_password', nargs="?", metavar='<mysql_root_password>', default='', help="Password of MySQL root user")

    mysql_parser = subparsers.add_parser('recover_ha', help='recover ha')

    sso_parser = subparsers.add_parser('set_sso', help='configure sso on or off')
    sso_parser.add_argument("--stat", metavar='<sso_stat>', required=True, help="on | off")

    if (len(sys.argv) == 1):
        parser.print_help()
        exit(1)

    args = parser.parse_args(sys.argv[1:])
    ctrlm = CtrlManage()
    method = getattr(ctrlm, args.subcommand)
    return method(args)

    
if __name__ == '__main__':
    main()
